//
//  TopicViewController.m
//  滴滴快拍
//
//  Created by dllo on 16/5/28.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "TopicViewController.h"

@interface TopicViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>

@property (nonatomic, strong) BaseCollectionView *perContentCollection;
@property (nonatomic, strong) NSMutableArray *perContentArr;
@property (nonatomic, assign) NSInteger page;


@end

@implementation TopicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.navigationItem.title = [self.topicnameEncodingStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self createView];
    [self createData];
}

#pragma mark 创建每页的内容collection
- (void)createView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 15) / 2, SCREEN_HEIGHT / 3);
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 创建collection
    self.perContentCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) collectionViewLayout:layout];
    [self.view addSubview:self.perContentCollection];
    //  设置代理
    self.perContentCollection.delegate = self;
    self.perContentCollection.dataSource = self;
    // 注册
    [self.perContentCollection registerClass:[AGLChannelCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLChannelCollectionCell class])];
    
    [self.perContentCollection registerClass:[AGLTopicCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLTopicCollectionCell class])];
    
}

#pragma mark 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.perContentArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"%@", NSStringFromClass([self.perContentArr[indexPath.item] class]));
    NSString *className = NSStringFromClass([self.perContentArr[indexPath.item] class]);
    //    Class class = NSClassFromString(className);
    
    //    if ([[class class] isKindOfClass:[AGLChannel class]]) {
    if ([className isEqualToString:@"AGLChannel"]) {
        
        AGLChannelCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLChannelCollectionCell class]) forIndexPath:indexPath];
        AGLChannel *channel = self.perContentArr[indexPath.item];
        cell.channel = channel;
        
        return cell;
        
    } else {
        AGLTopicCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLTopicCollectionCell class]) forIndexPath:indexPath];
        AGLTopic *topic = self.perContentArr[indexPath.item];
        cell.topic = topic;
        
        return cell;
        
    }
    
}

#pragma mark 点击小cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    AGLChannel *channel = self.perContentArr[indexPath.item];
    
    VideoDetailViewController *vidoeDetailVC = [[VideoDetailViewController alloc] init];
    vidoeDetailVC.scid = channel.scid;
    //                vidoeDetailVC.videoURL = [NSURL URLWithString:videoURLStr];
    vidoeDetailVC.videoURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://gslb.miaopai.com/stream/%@.mp4", channel.scid]];
    vidoeDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vidoeDetailVC animated:YES];
    vidoeDetailVC.hidesBottomBarWhenPushed = YES;
    

    
}


#pragma mark 请求数据
- (void)createData {
    
    //1.下拉刷新
    self.perContentCollection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.page = 1;
        //        if (_outTimer) {
        //            [_outTimer invalidate];
        //            _outTimer = nil;
        //        }
        //        self.outTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(showNetWorkBad) userInfo:nil repeats:NO];
        [self recieveData];
    }];
    
    //2.上拉加载
    self.perContentCollection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self recieveData];
    }];
    // 马上进入刷新状态
    [self.perContentCollection.mj_header beginRefreshing];
    
}
//-(void)showNetWorkBad{
//    if (_outTimer) {
//        [_outTimer invalidate];
//        _outTimer = nil;
//    }
//    [self.perContentCollection.mj_header endRefreshing];
//}


- (void)recieveData {
    
    
    NSString *urlString = [NSString string];
    if (self.topicnameEncodingStr == nil) {
        urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/v2_topic.json?os=android&udid=cb88ab16-2053-311d-8cc4-599086675743&type=2&version=6.3.9&timestamp=1464428654928&unique_id=cb88ab16-2053-311d-8cc4-599086675743&per=20&page=%ld&token=FAvwTuEEUuHAV6JfgDvWYC-gGk6GSp0c&vend=miaopai&uuid=cb88ab16-2053-311d-8cc4-599086675743&channel=yixia&deviceId=cb88ab16-2053-311d-8cc4-599086675743&stpid=%@", self.page, self.stpid];
    } else {
        urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/v2_topic.json?os=android&udid=cb88ab16-2053-311d-8cc4-599086675743&type=0&version=6.3.9&timestamp=1464427900868&unique_id=cb88ab16-2053-311d-8cc4-599086675743&per=20&page=%ld&token=FAvwTuEEUuHAV6JfgDvWYC-gGk6GSp0c&vend=miaopai&topicname=%@&uuid=cb88ab16-2053-311d-8cc4-599086675743&channel=yixia&deviceId=cb88ab16-2053-311d-8cc4-599086675743&stpid=%@", self.page, self.topicnameEncodingStr, self.stpid];
        
    }
    NSLog(@"%@", urlString);
    // 请求分类
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        [self saveData:responseObject DataName:@"hotMovieTable"];
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        self.navigationItem.title = dic[@"topic"];
        
        NSArray *result = dic[@"result"];
//        self.perContentArr = [NSMutableArray array];
        NSMutableArray *array = [NSMutableArray array];

        
        for (NSDictionary *temp in result) {
                AGLChannel *channel = [[AGLChannel alloc] init];
                [channel setValuesForKeysWithDictionary:temp];
                [array addObject:channel];
        }
        if (self.page == 1) {
            self.perContentArr = [NSMutableArray arrayWithArray:array];
        } else {
            [self.perContentArr addObjectsFromArray:array];
        }
        self.page += 1;
        // 刷新表格
        [self.perContentCollection.mj_header endRefreshing];
        [self.perContentCollection.mj_footer endRefreshing];


        [self.perContentCollection reloadData];
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"话题内容collection联网失败");
        [self.perContentCollection.mj_header endRefreshing];
        [self.perContentCollection.mj_footer endRefreshing];

        //        NSDictionary *dic = [self getDataWithDataName:@"hotMovieTable"];
        //        if (dic == nil) {
        //            NSLog(@"请连网啊亲");
        //        } else {
        //            NSDictionary *data = dic[@"data"];
        //            NSArray *hot = data[@"hot"];
        //            self.movieArr = [AGLMovie baseModalByArr:hot];
        //            [self.tableView reloadData];
        //        }
        //        
        
    }];
    
    
}
-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
